package com.eleme.cart.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eleme.cart.dto.CartAddDTO;
import com.eleme.cart.dto.CartUpdateDTO;
import com.eleme.cart.entity.Cart;
import com.fusion.eleme.cart.mapper.CartItemMapper;
import com.eleme.cart.mapper.CartMapper;
import com.eleme.cart.service.CartService;
import com.eleme.cart.vo.CartItemVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import io.seata.spring.annotation.GlobalTransactional;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private CartMapper cartItemMapper;

    @Override
    @GlobalTransactional(name = "cart-add-transaction", rollbackFor = Exception.class)
    public String addItem(CartAddDTO dto) {
        QueryWrapper<Cart> query = new QueryWrapper<>();
        query.eq("user_id", dto.getUserId()).eq("food_id", dto.getFoodId());
        Cart exist = cartItemMapper.selectOne(query);
        if (exist != null) {
            exist.setQuantity(exist.getQuantity() + dto.getQuantity());
            cartItemMapper.updateById(exist);
            return "购物车数量已更新";
        }
        Cart item = new Cart();
        BeanUtils.copyProperties(dto, item);
        item.setId(UUID.randomUUID().toString().replace("-", ""));
        cartItemMapper.insert(item);
        return "添加成功";
    }

    @Override
    @GlobalTransactional(name = "cart-update-transaction", rollbackFor = Exception.class)
    public String updateItem(CartUpdateDTO dto) {
        Cart item = cartItemMapper.selectById(dto.getId());
        if (item == null) throw new RuntimeException("购物车条目不存在");
        item.setQuantity(dto.getQuantity());
        cartItemMapper.updateById(item);
        return "数量已更新";
    }

    @Override
    @GlobalTransactional(name = "cart-remove-transaction", rollbackFor = Exception.class)
    public String removeItem(String id) {
        int rows = cartItemMapper.deleteById(id);
        if (rows == 0) throw new RuntimeException("购物车条目不存在");
        return "已移除";
    }

    @Override
    @GlobalTransactional(name = "cart-clear-transaction", rollbackFor = Exception.class)
    public String clearCart(String userId) {
        QueryWrapper<Cart> query = new QueryWrapper<>();
        query.eq("user_id", userId);
        cartItemMapper.delete(query);
        return "购物车已清空";
    }

    @Override
    public List<CartItemVO> listByUser(String userId) {
        QueryWrapper<Cart> query = new QueryWrapper<>();
        query.eq("user_id", userId);
        List<Cart> list = cartItemMapper.selectList(query);
        List<CartItemVO> res = new ArrayList<>();
        for (Cart c : list) {
            CartItemVO vo = new CartItemVO();
            BeanUtils.copyProperties(c, vo);
            res.add(vo);
        }
        return res;
    }
} 